#include "node.h"
#include <algorithm>

using namespace kraw;


std::vector<ObjectNode*> ObjectNode::toDelete;

ObjectNode::ObjectNode() :
parent(NULL)
{
}

void ObjectNode::addChild(ObjectNode* child)
{
	if (child->parent)
		child->parent->removeChild(child);

	child->parent = this;
	
	children.push_back(child);
}

void ObjectNode::addChildAt(ObjectNode *child, int index)
{
    if (child->parent)
		child->parent->removeChild(child);
    
	child->parent = this;
    children.insert(children.begin() + index, child); //check boundaries?
}

void ObjectNode::removeChild(ObjectNode* child)
{
	std::vector<ObjectNode*>::iterator it = std::find(children.begin(), children.end(), child);
    if (it == children.end())
        return;
    
    children.erase(it);
    child->parent = NULL;
}

void ObjectNode::deleteChild(ObjectNode *child)
{
    removeChild(child);
    
	if (std::find(toDelete.begin(), toDelete.end(), child) == toDelete.end())
		toDelete.push_back(child);
}

ObjectNode* ObjectNode::findChildByName(const std::string& name)
{
    int numChilds = children.size();
    for (int i = 0; i < numChilds; i++)
    {
        ObjectNode* child = children[i];
        if (child->name == name)
            return child;
    }

    return NULL;
}

ObjectNode* ObjectNode::getChildAt(int index)
{
	if (index >=0 && index < children.size())
		return children[index];
	
	return NULL;
}

int ObjectNode::getChildCount()
{
	return children.size();
}

void ObjectNode::deleteTraversal()
{
    size_t numChilds = children.size();
    for (size_t i = 0; i < numChilds; i++)
    {
        children[i]->deleteTraversal();
        delete children[i];
    }

	children.clear();
}

void ObjectNode::deletePendingNodes()
{
	std::vector<ObjectNode*> toDeleteCopy = toDelete;
	toDelete.clear();

	std::vector<ObjectNode*>::iterator it;
	for (it = toDeleteCopy.begin(); it != toDeleteCopy.end(); it++)
	{
		ObjectNode* object = (*it);
		object->deleteTraversal();
        delete object;
	}
}

void ObjectNode::release()
{
	if (parent)
	{
		parent->removeChild(this);
		//LOGI("Warning: Destroying an object with parent (parent should delete this object)");
	}

	deleteTraversal();
	delete this;
}

void ObjectNode::logicTraversal()
{
	for (size_t i = 0; i < children.size(); ++i)
	{
        children[i]->logicTraversal();
	}

    logicUpdate();
}

void ObjectNode::logicUpdate()
{
	//...
}
